﻿#include "FSM.h"

void FSM::transferState(FSMItem::State nextState)
{
    _curState = nextState;
}

void FSM::handleEvent(FSMItem::Events event)
{
    FSMItem::State curState = _curState;   //现态
    void(*action)() = nullptr;  //动作
    FSMItem::State nextState;   //次态
    bool flag = false;
    for(int i=0;i < _fsmTable.size();i++)
    {
        if(event==_fsmTable[i]->_event&&curState==_fsmTable[i]->_curState)
        {
            flag=true;
            action=_fsmTable[i]->_action;
            nextState=_fsmTable[i]->_nextState;
            break;
        }
    }

    //找到对应的状态，执行动作，状态转移
    if(flag)
    {
        if(action)
        {
            action();
        }
        transferState(nextState);
    }
    
}

void FSM::initFSMTable()
{
    _fsmTable.push_back(new FSMItem(FSMItem::GETUP, FSMItem::EVENT1, &FSMItem::getUp, FSMItem::GOTOSCHOOL));
    _fsmTable.push_back(new FSMItem(FSMItem::GOTOSCHOOL, FSMItem::EVENT2, &FSMItem::gotoSchool, FSMItem::HAVELUNCH));
    _fsmTable.push_back(new FSMItem(FSMItem::HAVELUNCH, FSMItem::EVENT3, &FSMItem::haveLunch, FSMItem::DOHOMEWORK));
    _fsmTable.push_back(new FSMItem(FSMItem::DOHOMEWORK, FSMItem::EVENT1, &FSMItem::doHomework, FSMItem::SLEEP));
    _fsmTable.push_back(new FSMItem(FSMItem::SLEEP, FSMItem::EVENT2, &FSMItem::sleeping, FSMItem::GETUP));
}



